//
//  HJPayTransferController.m
//  KaiChat
//
//  Created by lx on 2024/1/23.
//

#import "HJPayTransferController.h"
#import "HJGradientView.h"
#import "HJTitleTextField.h"
#import "HJMinePresent.h"
#import "HJPayResultController.h"
#import "HJChatMessageModel.h"
#import "HJIM.h"
#import "HJPayPasswordController.h"
#import "HJErrorTipView.h"
#import "HJAlertController.h"
#import "HJPaySendCodeController.h"
#import "HJBindingAccountController.h"
#import "HJWebSocketManager.h"

@interface HJPayTransferController ()<QMUITextFieldDelegate>

@property (nonatomic, weak) HJStyle1Button *confirmButton;
@property (nonatomic, weak) HJTitleTextField *amountTextField;
@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, weak) UILabel *uidLabel;
@property (nonatomic, weak) UILabel *balanceLabel;
@property (nonatomic, weak) HJErrorTipView *tipView;
@property (nonatomic, assign) CGFloat tipViewH;
@property (nonatomic, copy) NSString *balance;
@property (nonatomic, assign) BOOL showBalanceErrorTip;



@end

@implementation HJPayTransferController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.alpha = 0;
    self.navigationBar.title = @"KaiPay Transfer";
    
    UIImageView *logoImageView = [UIImageView addToView:self.navigationBar.contentView];
    logoImageView.image = [UIImage imageNamed:@"transferLogo"];
    [logoImageView addTapGesturesWithTarget:self action:@selector(tapLogoImageView)];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.centerY.offset(0);
        make.width.offset(74);
        make.height.offset(24);
    }];
    
    HJGradientView *topView = [HJGradientView addToView:self.view];
    topView.colors = @[UIColorMake(0xE7E1FF), UIColorMake(0xFFFFFF)];
    [topView setStartPoint:CGPointZero endPoint:CGPointMake(0, 1)];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(212 + KNavBarHight);
    }];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:self.view font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:[NSString stringWithFormat:@"Transfer to %@", _sessionModel.sessionName] textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight + 24);
        make.left.offset(leftRightMargin);
        make.right.mas_lessThanOrEqualTo(-leftRightMargin - 46);
    }];
    
    UILabel *uidLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_868391Color title:@"UID:" textAlignment:NSTextAlignmentLeft];
    [uidLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(textSubTextLabelMargin);
        make.left.equalTo(titleLabel);
        make.right.inset(leftRightMargin);
    }];
    
    UIImageView *avatarImageView = [UIImageView addToView:self.view];
    avatarImageView.addCornerRadius(23);
    avatarImageView.layer.borderColor = UIColor.whiteColor.CGColor;
    avatarImageView.layer.borderWidth = 1;
    [avatarImageView tj_setImageWithURL:_sessionModel.sessionAvatar.URL placeholderImage:[UIImage imageNamed:@"avatar"]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.height.offset(46);
        make.top.equalTo(titleLabel);
    }];
    
    UIView *contentView = [[UIView alloc] init].addTo(self.view);
    contentView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - KNavBarHight - 87);
    contentView.layer.mask = [contentView shapeLayerRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    contentView.backgroundColor = UIColor.whiteColor;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(87 + KNavBarHight);
        make.left.right.offset(0);
        make.bottom.offset(0);
    }];
    
    HJTitleTextField *amountTextField = [HJTitleTextField addToView:contentView];
    amountTextField.titleLabel.text = @"Transfer Amount";
    amountTextField.textField.placeholder = @"0.00";
    amountTextField.titleLabel.textColor = UIColor.tj_333333Color;
    amountTextField.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    amountTextField.textField.keyboardType = UIKeyboardTypeDecimalPad;
    amountTextField.textField.delegate = self;
    [amountTextField.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [amountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(20);
        make.height.offset(72);
    }];
    [amountTextField.textField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.inset(68);
    }];
    
    UILabel *unitLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(14) color:UIColor.tj_333333Color title:@"USDT" textAlignment:NSTextAlignmentLeft];
    [unitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(amountTextField.textField);
        make.right.equalTo(amountTextField).inset(15);
    }];
    
    UILabel *balanceLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_333333Color title:@"Balance: 889.89USDT" textAlignment:NSTextAlignmentLeft];
    [balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(amountTextField.mas_bottom).offset(12);
        make.left.inset(15);
    }];
    
    HJErrorTipView *tipView = [[HJErrorTipView alloc] initWithText:@"The current amount is insufficient, please re-enter!" showCloseButton:NO];
    [self.view addSubview:tipView];
    tipView.hidden = YES;
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(balanceLabel.mas_bottom).offset(10);
        make.left.right.inset(leftRightMargin);
    }];
    
    HJStyle1Button *confirmButton = [HJStyle1Button buttonWithSuperView:contentView font:UIFontMediumMake(14) color:nil title:@"Confirm"];
    confirmButton.enabled = NO;
    [confirmButton addTarget:self action:@selector(didClickConfirmButton) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(20);
        make.height.offset(buttonHeight);
        make.top.equalTo(balanceLabel.mas_bottom).offset(40);
    }];
    
    _confirmButton = confirmButton;
    _amountTextField = amountTextField;
    _avatarImageView = avatarImageView;
    _uidLabel = uidLabel;
    _balanceLabel = balanceLabel;
    _tipView = tipView;
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    _tipViewH = ceil(tipView.tj_height);
    
    dispatch_async_sql_queue(^{
        HJUserModel *userModel = [HJUserModel currentAccountModel];
        HJChatSessionModel *chatSessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId];
        
        dispatch_async_main_queue(^{
            self.balance = Dividing_powl(userModel.USDTBalance, 10, 6);
            if (chatSessionModel.sessionUserd) {
                self.uidLabel.text = [NSString stringWithFormat:@"UID:%@", chatSessionModel.sessionUid];
            }
            [[SDWebImageManager sharedManager] loadImageWithURL:chatSessionModel.sessionAvatar.URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    self.avatarImageView.image = image;
                }
            }];
        });
    });
    
    [self loadData];
    [self loadBalanceData];
}

- (void)tapLogoImageView {
    [[NSNotificationCenter defaultCenter] postNotificationName:openKaiPayNotification object:nil];
}

- (void)setShowBalanceErrorTip:(BOOL)showBalanceErrorTip {
    _showBalanceErrorTip = showBalanceErrorTip;
    
    _confirmButton.enabled = !showBalanceErrorTip;
    
    if (showBalanceErrorTip) {
        self.tipView.hidden = NO;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        if (showBalanceErrorTip) {
            [self.tipView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(self.tipViewH);
            }];
            [self.confirmButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.inset(leftRightMargin);
                make.height.offset(buttonHeight);
                make.top.equalTo(self.tipView.mas_bottom).offset(40);
            }];
        } else {
            [self.tipView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(0);
            }];
            [self.confirmButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.inset(leftRightMargin);
                make.height.offset(buttonHeight);
                make.top.equalTo(self.balanceLabel.mas_bottom).offset(40);
            }];
        }
        
        [self.confirmButton.superview setNeedsLayout];
        [self.confirmButton.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        if (!showBalanceErrorTip) {
            self.tipView.hidden = YES;
        }
    }];
    
}

- (void)setBalance:(NSString *)balance {
    _balance = balance;
    
    self.balanceLabel.attributedText = [[NSString stringWithFormat:@"Balance: %@ USDT", balance ?: @"0"] attributedStringWithRangeString:balance rangeColor:UIColor.tj_333333Color color:UIColor.tj_868391Color];
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    _confirmButton.enabled = textField.text.length && !_showBalanceErrorTip;
    
    BOOL isShow = textField.text.floatValue > _balance.floatValue;
    if (isShow == _showBalanceErrorTip) return;
    
    self.showBalanceErrorTip = textField.text.floatValue > _balance.floatValue;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *currentText = textField.text ?: @"";
    NSString *newText = [currentText stringByReplacingCharactersInRange:range withString:string];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(0(\\.\\d{0,6})?|[1-9]\\d{0,5}(\\.\\d{0,6})?)?$" options:NSRegularExpressionCaseInsensitive error:nil];
    NSRange textRange = NSMakeRange(0, newText.length);
    return [regex firstMatchInString:newText options:0 range:textRange];
}


- (void)didClickConfirmButton {
    [self.view endEditing:YES];
    
    [HJHUD showLoadingInView:self.view];
    
    NSString *amount = _amountTextField.textField.text;
    [HJMinePresent isSetPayPasswordComplete:^(BOOL res, NSError * _Nullable error) {
        if (error) {
            if ([error.domain isEqualToString:ERRPRDOMAIN] && error.code == selfNotBindingAccountCode) {
                [HJAlertController alertInController:self title:nil message:@"Your account does not have an email" left:^(HJAlertAction * _Nonnull action) {
                    action.title = @"Cancel";
                    action.titleColor = UIColor.tj_868391Color;
                } right:^(HJAlertAction * _Nonnull action) {
                    action.title = @"OK";
                    action.titleColor = UIColor.tj_mainColor;
                    [action setHandler:^{
                        HJBindingAccountController *bindingAccountController = [[HJBindingAccountController alloc] init];
                        [self presentViewController:bindingAccountController animated:YES completion:nil];
                    }];
                }];
                return;
            }
            return;
        }
        
        if (res) {
            [self prepareOrderWithFromUserId:HJUserInfo.userId value:amount];
        } else {
            [HJHUD hiddenLoadingInView:self.view];
            
            [HJAlertController alertInController:self title:nil message:@"You have not created a Kai pay transaction password. Heading to?" left:^(HJAlertAction * _Nonnull action) {
                action.title = @"Cancel";
                action.titleColor = UIColor.tj_868391Color;
            } right:^(HJAlertAction * _Nonnull action) {
                action.title = @"OK";
                action.titleColor = UIColor.tj_mainColor;
                [action setHandler:^{
                    HJPaySendCodeController *paySendCodeController = [[HJPaySendCodeController alloc] init];
                    [self.navigationController pushViewController:paySendCodeController];
                }];
            }];
        }
    }];
}

- (void)prepareOrderWithFromUserId:(NSString *)fromUserId  value:(NSString *)value {
    
    [self getToUserIdComplete:^(NSString * _Nullable toUserId) {
        
        [HJMinePresent prepareOrderWithFromUserId:fromUserId toUserId:toUserId value:value complete:^(NSString * _Nullable orderNo, NSError * _Nullable prepareOrderError) {
            
            if (prepareOrderError) {
                if ([prepareOrderError.domain isEqualToString:ERRPRDOMAIN] && prepareOrderError.code == otherNotBindingAccountCode) {
                    [HJAlertController alertInController:self title:nil message:@"Transfer unsuccessful. Recipient's email not set up." left:^(HJAlertAction * _Nonnull action) {
                        action.title = @"Cancel";
                        action.titleColor = UIColor.tj_868391Color;
                    } right:^(HJAlertAction * _Nonnull action) {
                        action.title = @"OK";
                        action.titleColor = UIColor.tj_mainColor;
                        [action setHandler:^{
                            [self dismissViewControllerAnimated:YES completion:nil];
                        }];
                    }];
                } else {
                    [HJHUD showErrorMessage:prepareOrderError.localizedFailureReason];
                }
                return;
            }
            
            [self payWithOrderId:orderNo];
        }];
    }];
}

- (void)payWithOrderId:(NSString *)orderId {
    
    HJPayPasswordController *payPasswordController = [[HJPayPasswordController alloc] init];
    [payPasswordController setInputComplete:^(NSString * _Nonnull password) {
        
        if (isEmptyString(password)) return;
        
        [HJHUD showLoadingInView:self.view];
        [HJMinePresent payWithOrderId:orderId password:password complete:^(NSDictionary * _Nullable orderInfo, NSError * _Nullable payError) {
            if (orderInfo) {
                HJPayResultController *resultController = [[HJPayResultController alloc] init];
                resultController.userName = self.sessionModel.sessionName;
                [self.navigationController pushViewController:resultController];
                [self loadBalanceData];
            } else {
                NSDictionary *responseObject = payError.userInfo[@"responseObject"];
                if (!isEmptyString(responseObject[@"msg"])) {
                    [HJHUD showErrorMessage:responseObject[@"msg"]];
                    return;
                }
                
                HJPayResultController *resultController = [[HJPayResultController alloc] init];
                resultController.userName = self.sessionModel.sessionName;
                resultController.isError = YES;
                [self.navigationController pushViewController:resultController];
            }
        }];
        
    }];
    
    [payPasswordController setChangePassword:^{
        HJPaySendCodeController *paySendCodeController = [[HJPaySendCodeController alloc] init];
        [self.navigationController pushViewController:paySendCodeController];
    }];
    [payPasswordController showInController:self];
}


- (void)loadBalanceData {
    [HJMinePresent getKaiPayBalanceComplete:^(NSString * _Nullable balance, NSError * _Nullable error) {
        if (error) return;
        
        dispatch_async_sql_queue(^{
            HJUserModel *userModel = [HJUserModel currentAccountModel];
            userModel.USDTBalance = balance;
            [userModel bg_saveOrUpdate];
        });
        
        self.balance = Dividing_powl(balance, 10, 6);
    }];
}

- (void)getToUserIdComplete:(void (^)(NSString * _Nullable toUserId))complete {
    
    if (self.sessionModel.sessionUserd) {
        complete(self.sessionModel.sessionUserd);
        return;
    }
    
    [HJIM.shareIM.conversationManager loadConversatioInfoWithSessionId:self.sessionModel.sessionId type:self.sessionModel.chatType completion:^(HJChatSessionModel * _Nonnull sessionModel) {
        
        if (!sessionModel) {
            complete(nil);
            return;
        };
        
        HJChatSessionModel *chatSessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:sessionModel.sessionId];
        chatSessionModel.isTop = sessionModel.isTop;
        chatSessionModel.sessionAvatar = sessionModel.sessionAvatar;
        chatSessionModel.sessionUserd = sessionModel.sessionUserd;
        chatSessionModel.isMute = sessionModel.isMute;
        chatSessionModel.isTop = sessionModel.isTop;
        chatSessionModel.sessionUid = sessionModel.sessionUid;
        [chatSessionModel bg_saveOrUpdateAsync:nil];
        
        complete(chatSessionModel.sessionUserd);

        self.sessionModel.sessionUid = chatSessionModel.sessionUid;
        self.sessionModel.sessionUserd = chatSessionModel.sessionUserd;

        self.uidLabel.text = [NSString stringWithFormat:@"UID:%@", sessionModel.sessionUid];
        [[SDWebImageManager sharedManager] loadImageWithURL:self.sessionModel.sessionAvatar.URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image) {
                self.avatarImageView.image = image;
            }
        }];
    }];
    
}

- (void)loadData {
    
    if (!self.sessionModel.sessionUserd || !self.sessionModel.sessionUid || !self.sessionModel.sessionAvatar) {//查询会话信息
        
        [HJIM.shareIM.conversationManager loadConversatioInfoWithSessionId:self.sessionModel.sessionId type:self.sessionModel.chatType completion:^(HJChatSessionModel * _Nonnull sessionModel) {
            
            if (!sessionModel) return;
            
            HJChatSessionModel *chatSessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:sessionModel.sessionId];
            chatSessionModel.isTop = sessionModel.isTop;
            chatSessionModel.sessionAvatar = sessionModel.sessionAvatar;
            chatSessionModel.sessionUserd = sessionModel.sessionUserd;
            chatSessionModel.isMute = sessionModel.isMute;
            chatSessionModel.isTop = sessionModel.isTop;
            chatSessionModel.sessionUid = sessionModel.sessionUid;
            [chatSessionModel bg_saveOrUpdateAsync:nil];
            
            self.sessionModel.sessionUid = chatSessionModel.sessionUid;
            self.sessionModel.sessionUserd = chatSessionModel.sessionUserd;
            
            self.uidLabel.text = [NSString stringWithFormat:@"UID:%@", sessionModel.sessionUid];
            [[SDWebImageManager sharedManager] loadImageWithURL:self.sessionModel.sessionAvatar.URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    self.avatarImageView.image = image;
                }
            }];
        }];
    }
    
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (void)test {
    
   
//                NSString *msg = toString(orderInfo[@"msg_id"]);
//
//                HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
   
//                messageModel.chatType = HJChatTypeSingle;
//                messageModel.messageType = HJMessageTypeTransfer;
//                messageModel.sessionId = toString(orderInfo[@"session_id"]);
//                messageModel.msgId = msg;
//                messageModel.senderId = HJUserInfo.userId;
//                messageModel.senderNickname = HJUserInfo.nickname;
//                messageModel.receiverId = HJUserInfo.userId;
//                messageModel.receiverNickname = HJUserInfo.nickname;
//                messageModel.orderStatus = [orderInfo[@"order_status"] integerValue];
//                messageModel.orderType = [orderInfo[@"order_type"] integerValue];
//                messageModel.orderId = toString(orderInfo[@"order_id"]);
//                messageModel.payCoin = orderInfo[@"pay_coin"];
//                messageModel.amount = toString(orderInfo[@"value"]);
//                messageModel.content = @"[Transfer]";
//
//                NSDictionary *describe = [orderInfo[@"describe"] mj_JSONObject];
//                messageModel.sessionUserd = toString(describe[@"toUid"]);
//                if ([msg isKindOfClass:NSDictionary.class]) {
//                    messageModel.msg = @{
//                        @"content": orderInfo
//                    }.mj_JSONString;
//                }
//                [HJIM.shareIM.chatManager insertMessageWithModel:messageModel completion:^{
//                    [[NSNotificationCenter defaultCenter] postNotificationName:inserMessageNotification object:messageModel];
//                }];
   
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}


@end
